package org.jpro.common.jpa.repository;

import java.io.Serializable;

import javax.persistence.EntityManager;

import org.jpro.common.bean.BaseEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

/**
 * <P>功能描述 : JpaRepository 创建工厂 </P>
 * <P>File name : JpaRepositoryFactoryBean </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/3/4 下午4:11</P>
 */
public class JpaRepositoryFactoryBean<R extends JpaRepository<T, I>, T extends BaseEntity, I extends Serializable>
        extends org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean<R, T, I> {
    /**
     * Creates a new {@link JpaRepositoryFactoryBean} for the given repository interface.
     * @param repositoryInterface must not be {@literal null}.
     */
    public JpaRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }

    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        return new IBaseRepository<T, I>(em);
    }

    private static class IBaseRepository<T extends BaseEntity, I extends Serializable> extends JpaRepositoryFactory {

        private final EntityManager em;

        IBaseRepository(EntityManager em) {
            super(em);
            this.em = em;
        }

        @Override
        protected Object getTargetRepository(RepositoryInformation information) {
            return new SimpleJpaRepository<T, I>((Class<T>) information.getDomainType(), em);
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return SimpleJpaRepository.class;
        }
    }

}
